import { ArgumentsHost, Catch, ExceptionFilter, NotFoundException } from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';

import { ErrorArgument } from '../../types';
import { getErrorRenderMapping } from '../../render';

@Catch()
export class CommonExceptionFilter implements ExceptionFilter {
    private readonly isDev: boolean;

    constructor(isDev: boolean) {
        this.isDev = isDev;
    }

    catch(exception: any, host: ArgumentsHost) {
        const context = host.switchToHttp();
        const request = context.getRequest() as FastifyRequest;
        const reply = context.getResponse() as FastifyReply;

        const args: ErrorArgument = { exception, request, reply, isDev: this.isDev };

        const errorRender = getErrorRenderMapping(exception?.status);
        const replyHtmlString = errorRender(args);

        // if (exception instanceof NotFoundException) {
        //     console.log('404');
        //     replyHtmlString = notFoundErrorRender(args);
        // }

        // if (exception instanceof ServerSideRenderError) {
        //     replyHtmlString = ssrErrorRender(args);
        // }
        reply.send(replyHtmlString);
    }
}
